﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Website;

namespace FRL.DebtChased.WebServices
{

	[ServiceContract(Namespace = "")]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class RichContentService
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		/////////////////////////////////////////////////////////////
		#region Operations - Workflow

		[OperationContract]
		public WorkflowTransportWrapper GetWorkflowXml(ref int iWorkflowId)
		{
#if DEBUG
			Debug.Assert(iWorkflowId != 0);
#endif // #if DEBUG

			// Declare return variable
			WorkflowTransportWrapper Ftmp = null;

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the workflow xml
				Ftmp = FRL.DebtChased.Repository.Workflow.GetWorkflowTransportWrapper(ent, iWorkflowId);

			}

			// Add your operation implementation here
			return Ftmp;

		}

		// Add more operations here and mark them with [OperationContract]
		[OperationContract]
		public string SetWorkflowXml(
			ref int iWorkflowId,
			byte[] buffer,
			int iAccountInvoiceStatusId
		)
		{

			// Declare return variable
			string strFtmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if(iUserId==0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the workflow template
				strFtmp = FRL.DebtChased.Repository.Workflow.SetXml(ent, ref iWorkflowId, buffer, iAccountInvoiceStatusId, iUserId);

			}

			// Return variable
			return strFtmp;

		}

		[OperationContract]
		public WorkflowsTransportWrapper GetWorkflowsTransportWrapper(int iClientId)
		{

			// Declare return variable
			WorkflowsTransportWrapper Ftmp = null;

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the workflow summary list
				Ftmp = FRL.DebtChased.Repository.Workflow.GetTransportWrapper( ent, iClientId );

			}

			// Add your operation implementation here
			return Ftmp;

		}

		[OperationContract]
		public WorkflowSupportData GetWorkflowSupportData()
		{

			// Declare return variable
			WorkflowSupportData Ftmp = new WorkflowSupportData();

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if (mySession.UserID == 0)
				mySession.SetDummySysAdmin();
#endif // #if DEBUG

			// Get the current user
			Ftmp.CurrentUser = new UserSessionTransport();
			mySession.LoadUserSessionTransport(Ftmp.CurrentUser);

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the comm-body list
				Ftmp.CommBodyList = CommBody.LoadTransportList(ent);

				// Load the popup dictionary
				Ftmp.PopupDictionary = Popup.LoadDictionary(ent);

				// Load the reusable strings
				Ftmp.PhoneCallReasons = ReusableString.Load(ent,Definitions.ReusableString_PhoneCallReasons);
				Ftmp.PhoneCallMessages = ReusableString.Load(ent, Definitions.ReusableString_PhoneCallMessages);

				// Load letter type dictionary
				Ftmp.LetterTypeDictionary = LetterType.GetDictionary(ent,true);

			}

			// Return variable
			return Ftmp;

		}

		[OperationContract]
		public string CreateInvoiceStatus(
			ref int iInvoiceStatusId, 
			string strInvoiceStatusName, 
			string strDefaultWorkflowName, 
			bool bIsInstalmentPlanStatus,
			bool bIsInQuery
		)
		{

			// Declare return variable
			string strError = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the invoice status
				strError = AccountInvoiceStatus.SetNew(
					ent, 
					ref iInvoiceStatusId, 
					strInvoiceStatusName, 
					strDefaultWorkflowName, 
					bIsInstalmentPlanStatus, 
					bIsInQuery,
					iUserId
				);

			}

			// Return variable
			return strError;

		}

		[OperationContract]
		public string SetInvoiceStatus(int iInvoiceStatusId, string strInvoiceStatusName, bool bIsInstalmentPlanStatus, bool bIsInQuery)
		{

			// Declare return variable
			string strError = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the invoice status
				strError = AccountInvoiceStatus.UpdateExisting(
					ent, 
					iInvoiceStatusId, 
					strInvoiceStatusName, 
					bIsInstalmentPlanStatus, 
					bIsInQuery,
					iUserId
				);

			}

			// Return variable
			return strError;

		}

		[OperationContract]
		public AccountInvoiceStatusTransport GetInvoiceStatus( int iInvoiceStatusId )
		{

			// Declare return variable
			AccountInvoiceStatusTransport Ftmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the invoice status
				Ftmp = AccountInvoiceStatus.GetTransport(ent, iInvoiceStatusId);

			}

			// Return variable
			return Ftmp;

		}

		#endregion Operations - Workflow

		/////////////////////////////////////////////////////////////
		#region Agent Editor Interface

		[OperationContract]
		public AgentTransport GetAgent(int iAgentId)
		{

			// Declare return variable
			AgentTransport Ftmp = null;

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the workflow xml
				Ftmp = FRL.DebtChased.Repository.Agent.GetAgentTransport(ent, iAgentId);

			}

			// Add your operation implementation here
			return Ftmp;

		}

		[OperationContract]
		public string SetAgent( ref AgentTransport agentTransport )
		{

			// Declare return variable
			string strFtmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the agent
				strFtmp = Agent.SetAgentTransport( ent, agentTransport, iUserId );
				if (strFtmp == null)
				{

					// Reload the agent
					agentTransport = Agent.GetAgentTransport(ent, agentTransport.AgentId);

				}

			}

			// Return variable
			return strFtmp;

		}

		[OperationContract]
		public AgentEditorSupportData GetAgentEditorSupportData()
		{

			// Declare return variable
			AgentEditorSupportData Ftmp = new AgentEditorSupportData();

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if (mySession.UserID == 0)
				mySession.SetDummySysAdmin();
#endif // #if DEBUG

			// Get the current user
			Ftmp.CurrentUser = new UserSessionTransport();
			mySession.LoadUserSessionTransport(Ftmp.CurrentUser);

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the country dictionary
				Ftmp.CountryDictionary = CountryCodes.Dictionary;

				// Load the reusable strings
				Ftmp.ContactTitles = ReusableString.Load(ent, Definitions.ReusableString_ContactTitles);
				Ftmp.ContactPositions = ReusableString.Load(ent, Definitions.ReusableString_ContactPositions);
				Ftmp.ContactCounties = ReusableString.Load(ent, Definitions.ReusableString_ContactCounties);
				Ftmp.BankNames = ReusableString.Load(ent, Definitions.ReusableString_BankNames);

			}

			// Return variable
			return Ftmp;

		}

		[OperationContract]
		public List<AgentSummaryTransport> SearchAgents(string strCountryCode)
		{

			// Declare return variable
			List<AgentSummaryTransport> Ftmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Search the agents
				Ftmp = Agent.TransportSearch(ent, strCountryCode, iUserId);

			}

			// Return variable
			return Ftmp;

		}

		#endregion Agent Editor Interface

		/////////////////////////////////////////////////////////////
		#region Client Editor Interface

		[OperationContract]
		public ClientTransport GetClient(int iClientId)
		{

			// Declare return variable
			ClientTransport Ftmp = null;

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the client transport
				Ftmp = FRL.DebtChased.Repository.Client.GetClientTransport(ent, iClientId);

			}

			// Add your operation implementation here
			return Ftmp;

		}

		[OperationContract]
		public string SetClient( ref ClientTransport clientTransport )
		{

			// Declare return variable
			string strFtmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the workflow template
				strFtmp = FRL.DebtChased.Repository.Client.SetClientTransport(ent, clientTransport, iUserId);
				if (strFtmp == null)
				{

					// Reload the client
					clientTransport = Client.GetClientTransport(ent, clientTransport.ClientId);

				}

			}

			// Return variable
			return strFtmp;

		}

		[OperationContract]
		public ClientEditorSupportData GetClientEditorSupportData()
		{

			// Declare return variable
			ClientEditorSupportData Ftmp = new ClientEditorSupportData();

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if(mySession.UserID == 0)
				mySession.SetDummyClient();
#endif // #if DEBUG

			// Get the current user
			Ftmp.CurrentUser = new UserSessionTransport();
			mySession.LoadUserSessionTransport(Ftmp.CurrentUser);

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the country dictionary
				Ftmp.CountryMap = CountryCodes.Dictionary;

				// Load the reusable strings
				Ftmp.ContactTitles = ReusableString.Load(ent, Definitions.ReusableString_ContactTitles);
				Ftmp.ContactPositions = ReusableString.Load(ent, Definitions.ReusableString_ContactPositions);
				Ftmp.ContactCounties = ReusableString.Load(ent, Definitions.ReusableString_ContactCounties);
				Ftmp.BankNames = ReusableString.Load(ent, Definitions.ReusableString_BankNames);

				// Load client activites
				Ftmp.ClientActivities = Client.GetActivities(ent);

				// Load finance teams
				Ftmp.FinanceTeamMap = FinanceTeam.GetDictionary(ent);

			}

			// Return variable
			return Ftmp;

		}

		[OperationContract]
		public List<ClientSummaryTransport> SearchClients(string strSearch)
		{

			// Declare return variable
			List<ClientSummaryTransport> Ftmp = new List<ClientSummaryTransport>();

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Search the clients
				Ftmp = Client.TransportSearch(ent, strSearch);

			}

			// Return variable
			return Ftmp;

		}

		#endregion Client Editor Interface

		/////////////////////////////////////////////////////////////
		#region Chase Workspace

		[OperationContract]
		public List<ChaseSessionItemTransport> GetChaseSessionItems()
		{

			// Declare return variable
			List<ChaseSessionItemTransport> Ftmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Call table function
				Ftmp = Account.LoadChaseSessionTransport(ent, iUserId);

			}

			// Return variable
			return Ftmp;

		}

		[OperationContract]
		public AccountTransport GetAccountTransport(int iAccountId)
		{

			// Declare return variable
			AccountTransport Ftmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Call table function
				Ftmp = Account.GetTransport(ent, iAccountId);

			}

			// Return variable
			return Ftmp;

		}

		[OperationContract]
		public ChaseWorkspaceSupportData GetChaseWorkspaceSupportData()
		{

			// Declare return variable
			ChaseWorkspaceSupportData Ftmp = new ChaseWorkspaceSupportData();

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if (mySession.UserID == 0)
				mySession.SetDummySysAdmin();
#endif // #if DEBUG

			// Get the current user
			Ftmp.CurrentUser = new UserSessionTransport();
			mySession.LoadUserSessionTransport(Ftmp.CurrentUser);

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the country dictionary
				Ftmp.CountryMap = CountryCodes.Dictionary;

				// Load the reusable strings
				Ftmp.ContactTitles = ReusableString.Load(ent, Definitions.ReusableString_ContactTitles);
				Ftmp.ContactPositions = ReusableString.Load(ent, Definitions.ReusableString_ContactPositions);
				Ftmp.ContactCounties = ReusableString.Load(ent, Definitions.ReusableString_ContactCounties);
				Ftmp.BankNames = ReusableString.Load(ent, Definitions.ReusableString_BankNames);

				// Load trading styles
				Ftmp.TradingStyleMap = AccountTradingStyle.GetDictionary(ent, true);

				// Load installment status map
				Ftmp.InstalmentStatusMap = AccountInvoiceStatus.GetInstalmentDictionary(ent, false);

				// Get current interest rate
				Ftmp.InterestRate = InterestRateHistory.GetCurrentRate(ent);

			}

			// Return variable
			return Ftmp;

		}

		[OperationContract]
		public string SetActiveAccountPlan( AccountPlanTransport accountPlan )
		{

			// Declare return variable
			string strError = null;

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if (mySession.UserID == 0)
				mySession.SetDummySysAdmin();
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Set the active account-plan
				strError = AccountPlan.SetActiveAccountPlan(ent,accountPlan,mySession.UserID);

			}

			// Return variable
			return strError;

		}

		[OperationContract]
		public string KillActiveAccountPlan(int iAccountPlanId, string strReason, bool bAlertManager)
		{

			// Declare return variable
			string strError = null;

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if (mySession.UserID == 0)
				mySession.SetDummySysAdmin();
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Set the active account-plan
				strError = AccountPlan.KillActiveAccountPlan(ent, iAccountPlanId, strReason, bAlertManager, mySession.UserID);

			}

			// Return variable
			return strError;

		}

		#endregion Chase Workspace

		/////////////////////////////////////////////////////////////
		#region Comm Body Editor Interface

		[OperationContract]
		public List<CommBodySummaryTransport> GetCommBodyList()
		{

			// Declare return variable
			List<CommBodySummaryTransport> Ftmp = null;

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the comm-body transport
				Ftmp = FRL.DebtChased.Repository.CommBody.LoadTransportList(ent);

			}

			// Add your operation implementation here
			return Ftmp;

		}

		[OperationContract]
		public CommBodyTransport GetCommBody(int iCommBodyId)
		{

			// Declare return variable
			CommBodyTransport Ftmp = null;

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load the comm-body transport
				Ftmp = FRL.DebtChased.Repository.CommBody.GetCommBodyTransport(ent, iCommBodyId);

			}

			// Add your operation implementation here
			return Ftmp;

		}

		[OperationContract]
		public string SetCommBody(ref CommBodyTransport commBodyTransport)
		{

			// Declare return variable
			string strFtmp = null;

			// Get the session id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the comm-body template
				strFtmp = FRL.DebtChased.Repository.CommBody.SetCommBodyTransport(ent, commBodyTransport, iUserId);
				if (strFtmp == null)
				{

					// Reload the comm-body
					commBodyTransport = CommBody.GetCommBodyTransport(ent, commBodyTransport.CommBodyId);

				}

			}

			// Return variable
			return strFtmp;

		}

		[OperationContract]
		public CommBodyEditorSupportData GetCommBodyEditorSupportData()
		{

			// Declare return variable
			CommBodyEditorSupportData Ftmp = new CommBodyEditorSupportData();

			// Get the session id
			MySession mySession = MySession.BindMySession();
#if DEBUG
			if (mySession.UserID == 0)
				mySession.SetDummySysAdmin();
#endif // #if DEBUG

			// Get the current user
			Ftmp.CurrentUser = new UserSessionTransport();
			mySession.LoadUserSessionTransport(Ftmp.CurrentUser);

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Load comm templates
				Ftmp.Templates = CommTemplate.LoadTransportList(ent);

			}

			// Return variable
			return Ftmp;

		}

		#endregion Comm Body Editor Interface

		[OperationContract]
		public void AddReusableString(string strCategory, string strValue, bool bAdd)
		{

			// Construct an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Call table function
				ReusableString.Add(ent, strCategory, strValue, bAdd);

			}

		}

        /////////////////////////////////////////////////////////////

        [OperationContract]
        public void AddAccountNote(AccountTransport account, AccountNoteTransport note)
        {
            // Get the session id
            MySession mySession = MySession.BindMySession();

            // Construct an entities object
            using (DebtChasedEntities ent = new DebtChasedEntities())
            {

                // Create a new account note
                AccountNote accountNote = AccountNote.Append(
                    ent,
                    account.AccountId,
                    note.Narrative,
                    null,
                    mySession.UserID,
                    AccountNote.eFlags.NotSet,
                    true,
                    false
                );

                ent.SaveChanges();
            }

        }

	}

}
